package cmd

import (
	"fmt"
	"gitee.com/ysfzf/zerox/helper"
	"github.com/spf13/cobra"
	"log"
	"os/exec"
	"path/filepath"
)

var genCmd = &cobra.Command{
	Use:   "gen",
	Short: "使用goctl生成go代码",
	Run: func(cmd *cobra.Command, args []string) {
		//调用系统命令
		dir, _ := cmd.Flags().GetString("dir")
		file, _ := cmd.Flags().GetString("file")
		if file == "" {
			//在当前目录查询第一个.api或者.proto文件
			allFile, err := helper.AllFile("./")
			if err != nil {
				log.Fatal(err)
				return
			}
			for _, f := range allFile {
				ext := filepath.Ext(f)
				if ext == ".api" || ext == ".proto" {
					file = f
					break
				}
			}
		}
		if file == "" {
			log.Fatal("没有找到可用的配置文件")
			return
		}
		tempDir := ""
		if helper.IsDir("./template") {
			tempDir = "--home=template"
		}
		ext := filepath.Ext(file)
		if ext == ".api" {
			file = "--api=" + file
			apiDir := "--dir=" + dir
			apiCmd := exec.Command("goctl", "api", "go", file, apiDir, tempDir)
			apiCmd.Stdout = cmd.OutOrStdout()
			apiCmd.Stderr = cmd.ErrOrStderr()
			apiCmd.Run()
		}

		if ext == ".proto" {
			goOut := "--go_out=" + dir
			grpcOut := "--go-grpc_out=" + dir
			zrpcOut := "--zrpc_out=" + dir
			fmt.Printf("goctl rpc protoc %s %s %s %s %s\n", file, goOut, grpcOut, zrpcOut, tempDir)
			protoCmd := exec.Command("goctl", "rpc", "protoc", file, goOut, grpcOut, zrpcOut, tempDir)
			protoCmd.Stdout = cmd.OutOrStdout()
			protoCmd.Stderr = cmd.ErrOrStderr()
			protoCmd.Run()
		}

	},
}

func init() {
	genCmd.Flags().StringP("file", "f", "", "using .api file or .proto file")
	//genCmd.Flags().StringP("proto", "p", "", "Generate gRpc code using .proto file")
	genCmd.Flags().StringP("dir", "d", ".", "The target dir")

	rootCmd.AddCommand(genCmd)
}
